#include "help_window.h"
#include "ui_manager.h"
#include "../app/main_app.h"
#include "function_button_manager.h"
#include "../config/config.h"
#include <iostream>
#include <fstream>
#include <sstream>


HelpWindow::HelpWindow() {
    builder = nullptr;
    window = nullptr;
    helpTreeView = nullptr;
    popupMenu = nullptr;
}

HelpWindow::~HelpWindow() {
    if (builder) {
        g_object_unref(builder);
    }
}

bool HelpWindow::init() {
    // 创建GtkBuilder
    builder = gtk_builder_new();
    
    // 获取UI文件路径
    char* exec_path = g_file_read_link("/proc/self/exe", NULL);
    char* ui_path = nullptr;
    
    if (exec_path) {
        char* exec_dir = g_path_get_dirname(exec_path);
        ui_path = g_build_filename(exec_dir, "UI", "help_window.glade", NULL);
        g_free(exec_dir);
        g_free(exec_path);
    } else {
        ui_path = g_strdup("UI/help_window.glade");
    }
    
    std::string ui_path_str = ui_path ? std::string(ui_path) : "UI/help_window.glade";
    std::cout << "尝试加载UI文件: " << ui_path_str << std::endl;
    
    // 从文件加载UI
    GError *error = nullptr;
    if (!gtk_builder_add_from_file(builder, ui_path_str.c_str(), &error)) {
        std::cerr << "无法加载UI文件 " << ui_path_str << ": " << error->message << std::endl;
        g_error_free(error);
        g_object_unref(builder);
        builder = nullptr;
        g_free(ui_path);
        return false;
    }
    g_free(ui_path);
    
    // 获取窗口对象
    window = GTK_WIDGET(gtk_builder_get_object(builder, "help_window"));
    if (!window) {
        std::cerr << "无法获取help_window对象" << std::endl;
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }
    
    // 连接信号
    gtk_builder_connect_signals(builder, nullptr);
    
    // 获取helpTextView对象
    std::cout << "正在尝试获取helpTextView对象..." << std::endl;
    GObject *treeViewObj = gtk_builder_get_object(builder, "helpTextView");
    if (treeViewObj) {
        std::cout << "成功获取到helpTextView对象指针" << std::endl;
        helpTreeView = GTK_WIDGET(treeViewObj);
        
        // 创建一个简单的列表存储模型
        GtkListStore *store = gtk_list_store_new(1, G_TYPE_STRING);
        gtk_tree_view_set_model(GTK_TREE_VIEW(helpTreeView), GTK_TREE_MODEL(store));
        g_object_unref(store);
        
        // 添加一列到TreeView
        GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
        // 设置行高和内边距
        g_object_set(renderer, "ypad", 0, NULL);
        g_object_set(renderer, "height", 20, NULL);
        // 默认不设置为可编辑，只在需要时启用
        g_object_set(renderer, "editable", FALSE, NULL);
        // 连接编辑完成的信号
        g_signal_connect(renderer, "edited", G_CALLBACK(on_cell_edited), this);
        
        GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes(
            "帮助内容", renderer, "text", 0, NULL);
        // 设置列为固定大小
        gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED);
        gtk_tree_view_column_set_fixed_width(column, 200); // 设置合适的宽度
        gtk_tree_view_append_column(GTK_TREE_VIEW(helpTreeView), column);
        
        // 启用固定高度模式以提高性能
        gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW(helpTreeView), TRUE);
        
        // 创建右键菜单
        create_popup_menu();
        
        // 连接右键点击事件
        g_signal_connect(helpTreeView, "button-press-event", G_CALLBACK(on_treeview_button_press_event), this);
        
        // 连接双击事件
        g_signal_connect(helpTreeView, "row-activated", G_CALLBACK(on_treeview_row_activated), this);
        
        // 禁用列的可编辑属性，避免与双击事件冲突
        gtk_tree_view_set_enable_tree_lines(GTK_TREE_VIEW(helpTreeView), FALSE);
        
        // 获取可执行文件目录
        char* execPath = g_file_read_link("/proc/self/exe", NULL);
        if (execPath) {
            char* execDir = g_path_get_dirname(execPath);
            char* configFilePath = g_build_filename(execDir, "config", "cwhelp.ini", NULL);
            
            // 读取cwhelp.ini文件
            std::ifstream file(configFilePath);
            if (file.is_open()) {
                std::stringstream contentStream;
                contentStream << file.rdbuf();
                std::string content = contentStream.str();
                file.close();
                
                // 将内容添加到TreeView中
                // 按行分割内容并添加到列表存储中
                std::istringstream iss(content);
                std::string line;
                while (std::getline(iss, line)) {
                    GtkTreeIter iter;
                    gtk_list_store_append(store, &iter);
                    gtk_list_store_set(store, &iter, 0, line.c_str(), -1);
                }
            } else {
                std::cerr << "无法打开cwhelp.ini文件: " << configFilePath << std::endl;
            }
            
            g_free(configFilePath);
            g_free(execDir);
            g_free(execPath);
        }
    } else {
        std::cerr << "无法获取helpTextView对象" << std::endl;
        // 尝试列出builder中的所有对象
        std::cout << "尝试列出builder中的所有对象..." << std::endl;
        GObject *helpWindowObj = gtk_builder_get_object(builder, "help_window");
        if (helpWindowObj) {
            std::cout << "成功获取到help_window对象" << std::endl;
        } else {
            std::cout << "无法获取到help_window对象" << std::endl;
        }
    }
    
    return true;
}

void HelpWindow::show() {
    if (window) {
        gtk_widget_show_all(window);
    }
}

void HelpWindow::hide() {
    if (window) {
        gtk_widget_hide(window);
    }
}

GtkWidget* HelpWindow::get_window() {
    return window;
}

void HelpWindow::create_popup_menu() {
    // 创建右键菜单
    popupMenu = gtk_menu_new();
    
    // 创建"编辑"菜单项
    GtkWidget *editMenuItem = gtk_menu_item_new_with_label("编辑");
    gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), editMenuItem);
    g_signal_connect(editMenuItem, "activate", G_CALLBACK(on_menu_edit_clicked), this);
    
    // 创建"保存"菜单项
    GtkWidget *saveMenuItem = gtk_menu_item_new_with_label("保存");
    gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), saveMenuItem);
    g_signal_connect(saveMenuItem, "activate", G_CALLBACK(on_menu_save_clicked), this);
    
    // 显示所有菜单项
    gtk_widget_show_all(popupMenu);
}

// 右键点击事件处理函数
gboolean HelpWindow::on_treeview_button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) {
    HelpWindow *helpWindow = static_cast<HelpWindow*>(data);
    
    // 检查是否是右键点击
    if (event->type == GDK_BUTTON_PRESS && event->button == 3) {
        // 显示右键菜单
        gtk_menu_popup_at_pointer(GTK_MENU(helpWindow->popupMenu), (GdkEvent*)event);
        return TRUE; // 停止事件传播
    }
    
    return FALSE; // 继续事件传播
}

// "编辑"菜单项点击处理函数
void HelpWindow::on_menu_edit_clicked(GtkMenuItem *menuitem, gpointer data) {
    HelpWindow *helpWindow = static_cast<HelpWindow*>(data);
    
    // 获取选中的行
    GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(helpWindow->helpTreeView));
    GtkTreeModel *model;
    GtkTreeIter iter;
    
    if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
        // 获取TreeView的列
        GList *columns = gtk_tree_view_get_columns(GTK_TREE_VIEW(helpWindow->helpTreeView));
        if (columns) {
            GtkTreeViewColumn *column = GTK_TREE_VIEW_COLUMN(columns->data);
            // 获取列中的渲染器并设置为可编辑
            GList *renderers = gtk_cell_layout_get_cells(GTK_CELL_LAYOUT(column));
            if (renderers) {
                GtkCellRenderer *renderer = GTK_CELL_RENDERER(renderers->data);
                g_object_set(renderer, "editable", TRUE, NULL);
                g_list_free(renderers);
            }
            
            // 直接使用我们创建的渲染器开始编辑当前选中行
            // 注意：这里假设我们只有一个渲染器，且它支持编辑
            gtk_tree_view_set_cursor(GTK_TREE_VIEW(helpWindow->helpTreeView), 
                                   gtk_tree_model_get_path(model, &iter),
                                   column, 
                                   TRUE);
            g_list_free(columns);
        }
    }
}

// "保存"菜单项点击处理函数
void HelpWindow::on_menu_save_clicked(GtkMenuItem *menuitem, gpointer data) {
    HelpWindow *helpWindow = static_cast<HelpWindow*>(data);
    helpWindow->save_treeview_content_to_file();
}

// 双击事件处理函数
gboolean HelpWindow::on_treeview_row_activated(GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, gpointer data) {
    HelpWindow *helpWindow = static_cast<HelpWindow*>(data);
    
    // 获取模型和迭代器
    GtkTreeModel *model = gtk_tree_view_get_model(tree_view);
    if (!model) {
        std::cerr << "无法获取TreeView模型" << std::endl;
        return FALSE;
    }
    
    GtkTreeIter iter;
    
    if (gtk_tree_model_get_iter(model, &iter, path)) {
        // 获取选中行的文本
        gchar *text;
        gtk_tree_model_get(model, &iter, 0, &text, -1);
        
        if (text) {
            // 通过UIManager获取主窗口的builder对象
            GtkBuilder *mainBuilder = UIManager::get_builder();
            if (mainBuilder) {
                // 获取edQSOMemo控件
                GtkWidget *edQSOMemo = GTK_WIDGET(gtk_builder_get_object(mainBuilder, "edQSOMemo"));
                if (edQSOMemo) {
                    // 获取文本缓冲区
                    GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(edQSOMemo));
                    if (buffer) {
                        std::string cw_str(text);
                        cw_str = trim(cw_str);
                        if(FunctionButtonManager::replaceCWStr(mainBuilder, cw_str) == 1){
                            // 设置文本内容
                            gtk_text_buffer_set_text(buffer, cw_str.c_str(), -1);
                        }
                    } else {
                        std::cerr << "无法获取edQSOMemo的文本缓冲区" << std::endl;
                    }
                } else {
                    std::cerr << "无法获取edQSOMemo控件" << std::endl;
                }
            } else {
                std::cerr << "无法获取主窗口builder对象" << std::endl;
            }
            g_free(text);
        } else {
            std::cerr << "无法获取选中行的文本" << std::endl;
        }
    } else {
        std::cerr << "无法获取TreeView迭代器" << std::endl;
    }
    
    return TRUE;
}

// 保存TreeView内容到文件
void HelpWindow::save_treeview_content_to_file() {
    if (!helpTreeView) return;
    
    // 获取TreeView的模型
    GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(helpTreeView));
    if (!model) return;
    
    // 获取可执行文件目录
    char* execPath = g_file_read_link("/proc/self/exe", NULL);
    if (execPath) {
        char* execDir = g_path_get_dirname(execPath);
        char* configFilePath = g_build_filename(execDir, "config", "cwhelp.ini", NULL);
        
        // 打开文件进行写入
        std::ofstream file(configFilePath);
        if (file.is_open()) {
            // 遍历所有行并写入文件
            GtkTreeIter iter;
            gboolean valid = gtk_tree_model_get_iter_first(model, &iter);
            
            while (valid) {
                gchar *text;
                gtk_tree_model_get(model, &iter, 0, &text, -1);
                
                if (text) {
                    file << text << std::endl;
                    g_free(text);
                }
                
                valid = gtk_tree_model_iter_next(model, &iter);
            }
            
            file.close();
            std::cout << "已保存帮助内容到文件: " << configFilePath << std::endl;
        } else {
            std::cerr << "无法打开文件进行写入: " << configFilePath << std::endl;
        }
        
        g_free(configFilePath);
        g_free(execDir);
        g_free(execPath);
    }
}

// 单元格编辑完成回调函数
void HelpWindow::on_cell_edited(GtkCellRendererText *renderer, gchar *path, gchar *new_text, gpointer data) {
    HelpWindow *helpWindow = static_cast<HelpWindow*>(data);
    
    // 获取TreeView的模型
    GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(helpWindow->helpTreeView));
    if (!model) return;
    
    // 根据路径字符串获取迭代器
    GtkTreeIter iter;
    if (gtk_tree_model_get_iter_from_string(model, &iter, path)) {
        // 更新模型中的值
        gtk_list_store_set(GTK_LIST_STORE(model), &iter, 0, new_text, -1);
    }
    
    // 编辑完成后，将渲染器的editable属性设置为FALSE
    g_object_set(renderer, "editable", FALSE, NULL);
}